package com.tian.service.impl.user;

import com.tian.common.util.CommonResult;
import com.tian.common.util.DateUtils;
import com.tian.common.util.UserCacheUtil;
import com.tian.dto.user.ChargeUserLoginResDto;
import com.tian.dto.user.InviteRecordRespDto;
import com.tian.dto.user.UserInvitedIncomeRespDto;
import com.tian.dto.user.UserInvitedRespDto;
import com.tian.mapper.ChargeInviteRecordMapper;
import com.tian.mapper.ChargeUserIncomeMapper;
import com.tian.service.user.UserInviteService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-12-06 16:22
 * {@code @version:} 1.0
 */
@Service
public class UserInviteServiceImpl implements UserInviteService {

    @Resource
    private ChargeInviteRecordMapper chargeInviteRecordMapper;
    @Resource
    private ChargeUserIncomeMapper chargeUserIncomeMapper;
    @Override
    public CommonResult<UserInvitedIncomeRespDto> getInviteIncome() {
        ChargeUserLoginResDto userInfoCache = UserCacheUtil.getUser();
        Long userId = userInfoCache.getId();
        UserInvitedIncomeRespDto userInvitedIncomeRespDto =   chargeUserIncomeMapper.selectSumByUserId(userId);
        if(userInvitedIncomeRespDto == null){
            return CommonResult.success(new UserInvitedIncomeRespDto());
        }
        return CommonResult.success(userInvitedIncomeRespDto);
    }

    @Override
    public CommonResult<UserInvitedRespDto> getInvited() {
        ChargeUserLoginResDto userInfoCache = UserCacheUtil.getUser();
        Long userId = userInfoCache.getId();
        int count = chargeInviteRecordMapper.countByUserId(userId);
        UserInvitedRespDto userInvitedRespDto = new UserInvitedRespDto();
        userInvitedRespDto.setInvitedCount(count);
        if(count == 0){
            return CommonResult.success(userInvitedRespDto);
        }
        List<InviteRecordRespDto> chargeInviteRecordList = chargeInviteRecordMapper.selectByUserId(userId);
        if(!CollectionUtils.isEmpty(chargeInviteRecordList)){
            for (InviteRecordRespDto inviteRecordRespDto : chargeInviteRecordList) {
                String invitedDateStr = DateUtils.format(inviteRecordRespDto.getInvitedDate(), DateUtils.FORMAT_DATE);
                inviteRecordRespDto.setInvitedDateStr(invitedDateStr);
            }
        }
        userInvitedRespDto.setData(chargeInviteRecordList);
        return CommonResult.success(userInvitedRespDto);
    }
}
